import { defineStore } from 'pinia'
import { ref } from 'vue'
import { attendanceApi } from '@/axios/api/attendance-records'
import { ElMessage } from 'element-plus'
import type { AttendanceRecord, AttendanceRecordCreate, AttendanceRecordUpdate } from '@/types/attendance'
import axios from 'axios'

// 导入BASE_URL常量
const BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8000'

// 创建考勤记录Store
export const useAttendanceStore = defineStore('attendance', () => {
  // 状态
  const attendanceRecords = ref<AttendanceRecord[]>([])
  const loading = ref(false)
  const currentRecord = ref<AttendanceRecord | null>(null)
  const totalRecords = ref(0)

  // 获取所有考勤记录
  const fetchAttendanceRecords = async () => {
    loading.value = true
    try {
      console.log('开始获取考勤记录列表')
      const response = await attendanceApi.getAttendanceRecords() as unknown as AttendanceRecord[]
      console.log('获取考勤记录列表响应:', response)
      
      // 检查返回的数据是否包含employee_name字段
      if (response && response.length > 0) {
        console.log('第一条记录:', JSON.stringify(response[0]))
        console.log('employee_name字段:', response[0].employee_name)
      } else {
        console.log('返回的数据为空或无记录')
      }
      
      attendanceRecords.value = response
      totalRecords.value = response.length
    } catch (error) {
      console.error('获取考勤记录列表失败:', error)
      ElMessage.error('获取考勤记录列表失败')
    } finally {
      loading.value = false
    }
  }

  // 获取单个考勤记录
  const fetchAttendanceRecord = async (id: number) => {
    loading.value = true
    try {
      console.log(`开始获取考勤记录 ${id}`)
      const response = await attendanceApi.getAttendanceRecord(id) as unknown as AttendanceRecord
      console.log(`获取考勤记录 ${id} 响应:`, response)
      currentRecord.value = response
      return response
    } catch (error) {
      console.error(`获取考勤记录 ${id} 失败:`, error)
      ElMessage.error(`获取考勤记录 ${id} 失败`)
      return null
    } finally {
      loading.value = false
    }
  }

  // 创建考勤记录
  const createAttendanceRecord = async (record: AttendanceRecordCreate) => {
    loading.value = true
    try {
      console.log('开始创建考勤记录:', record)
      const response = await attendanceApi.createAttendanceRecord(record) as unknown as AttendanceRecord
      console.log('创建考勤记录响应:', response)
      ElMessage.success('创建考勤记录成功')
      // 不自动刷新列表，由调用者决定是否刷新
      return response
    } catch (error: any) {
      console.error('创建考勤记录失败:', error)
      // 不在这里显示错误消息，而是向上抛出错误以便在组件中处理
      throw error
    } finally {
      loading.value = false
    }
  }

  // 批量创建考勤记录
  const batchCreateAttendanceRecords = async (records: AttendanceRecordCreate[]) => {
    loading.value = true
    try {
      console.log('开始批量创建考勤记录，数量:', records.length)
      const response = await attendanceApi.batchCreateAttendanceRecords(records) as unknown as {
        created_records: AttendanceRecord[],
        skipped_count: number,
        message: string
      }
      console.log('批量创建考勤记录响应:', response)
      
      // 显示成功消息，包含跳过的记录信息
      ElMessage.success(response.message)
      
      // 不自动刷新列表，由调用者决定是否刷新
      return response.created_records
    } catch (error: any) {
      console.error('批量创建考勤记录失败:', error)
      if (error.response?.data?.detail) {
        ElMessage.error(`批量创建考勤记录失败: ${error.response.data.detail}`)
      } else {
        ElMessage.error('批量创建考勤记录失败')
      }
      return null
    } finally {
      loading.value = false
    }
  }

  // 更新考勤记录
  const updateAttendanceRecord = async (id: number, record: AttendanceRecordUpdate) => {
    loading.value = true
    try {
      console.log(`开始更新考勤记录 ${id}:`, record)
      const response = await attendanceApi.updateAttendanceRecord(id, record) as unknown as AttendanceRecord
      console.log(`更新考勤记录 ${id} 响应:`, response)
      ElMessage.success('更新考勤记录成功')
      // 不自动刷新列表，由调用者决定是否刷新
      return response
    } catch (error) {
      console.error(`更新考勤记录 ${id} 失败:`, error)
      ElMessage.error(`更新考勤记录 ${id} 失败`)
      return null
    } finally {
      loading.value = false
    }
  }

  // 删除考勤记录
  const deleteAttendanceRecord = async (id: number) => {
    loading.value = true
    try {
      console.log(`开始删除考勤记录 ${id}`)
      await attendanceApi.deleteAttendanceRecord(id)
      console.log(`删除考勤记录 ${id} 成功`)
      ElMessage.success('删除考勤记录成功')
      // 不自动刷新列表，由调用者决定是否刷新
      return true
    } catch (error) {
      console.error(`删除考勤记录 ${id} 失败:`, error)
      ElMessage.error(`删除考勤记录 ${id} 失败`)
      return false
    } finally {
      loading.value = false
    }
  }

  // 批量更新考勤记录
  const batchUpdateAttendanceRecords = async (recordIds: number[], updateData: any) => {
    try {
      console.log('批量更新考勤记录:', recordIds, updateData)
      const response = await axios.patch(`${BASE_URL}/api/attendance-records/batch`, {
        record_ids: recordIds,
        update_data: updateData
      })
      console.log('批量更新考勤记录成功:', response.data)
      return response.data
    } catch (error) {
      console.error('批量更新考勤记录失败:', error)
      throw error
    }
  }

  // 批量删除考勤记录
  const batchDeleteAttendanceRecords = async (recordIds: number[]) => {
    try {
      console.log('批量删除考勤记录:', recordIds)
      const response = await axios.post(`${BASE_URL}/api/attendance-records/batch/delete`, {
        record_ids: recordIds
      })
      console.log('批量删除考勤记录成功:', response.data)
      return response.data
    } catch (error) {
      console.error('批量删除考勤记录失败:', error)
      throw error
    }
  }

  return {
    attendanceRecords,
    loading,
    currentRecord,
    totalRecords,
    fetchAttendanceRecords,
    fetchAttendanceRecord,
    createAttendanceRecord,
    batchCreateAttendanceRecords,
    updateAttendanceRecord,
    deleteAttendanceRecord,
    batchUpdateAttendanceRecords,
    batchDeleteAttendanceRecords
  }
}) 